﻿using Md.Api.DDD;
using Md.Api.Model;
using Newtonsoft.Json;

namespace Md.Api.Service;

/// <summary>
/// API统一抽象类
/// </summary>
/// <typeparam name="P">统一请求实体</typeparam>
public abstract class ApiBase<P> : ApiBaseBase<P> where P : RequestBaseModel, new()
{
    // 初始化异步锁
    private static SemaphoreSlim _mutex = new SemaphoreSlim(10);
    /// <summary>
    /// 登录用户信息标识，用户编号
    /// </summary>
    public object? userKey { get; set; }
    /// <summary>
    /// 平台 1管理系统 2PC 3H5 4小程序 5APP安卓 6APP苹果
    /// </summary>
    public object? platform { get; set; }
    /// <summary>
    /// 返回实体
    /// </summary>
    public ResponseMessageModel Result { get; set; } = new ResponseMessageModel();
    /// <summary>
    /// 参数
    /// </summary>
    public P Parameter { get; set; } = new P();
    /// <summary>
    /// 文件统一保存路径
    /// </summary>
    public string FileBasePath = JsonConfig.JsonRead("MdSettings:MdFilePath");
    /// 业务实现方法
    /// </summary>
    protected abstract void ExecuteMethod();
    /// <summary>
    /// 验证
    /// </summary>
    protected virtual bool Validate()
    {
        // 验签值不能为空
        //if (string.IsNullOrWhiteSpace(Parameter.Sign))
        //{
        //    Result.Code = "500";
        //    Result.Msg = "sign not be empty";
        //    Result.IsSuccess = false;

        //    return false;
        //}

        // 验签
        //if (!Parameter.Sign.Equals(GetMySign()))
        //{
        //    Result.Code = "500";
        //    Result.Msg = "sign fail";
        //    Result.IsSuccess = false;

        //    return false;
        //}

        // 获取token信息
        if (!string.IsNullOrWhiteSpace(Parameter.Token))
        {
            var tokenRes = JwtHelp.GetJwtDecode(Parameter.Token.Split(" ")[1]);

            if (tokenRes.Equals("token"))
            {
                Result.Code = "401";
                Result.Msg = tokenRes;
                Result.IsSuccess = false;

                return false;
            }

            var tokenDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(tokenRes);

            if (tokenDict != null && tokenDict.ContainsKey("userId"))
            {
                userKey = tokenDict["userId"].ToString();
                platform = tokenDict["platform"].ToString();
            }
        }
        
        return true;
    }
    /// <summary>
    /// 获取MySign
    /// </summary>
    private string GetMySign(string userkey = "5d39980acc6e4d6f91b04720c3414ef6")
    {
        var MerchantId = "MD2023";
        // MySign =(MerchantId = 12345 & TimesTamp = 2017 - 01 - 25 10:21:49 & Ip=167.0.12.31 & MAC = aaaa)+UserKey的值
        string MySign = EncrptyHelp.MD5Encrypt(string.Format(@"MerchantId={0}&TimesTamp={1}&Ip={2}&Mac={3}{4}"
                    , MerchantId
                    , Parameter.TimesTamp
                    , Parameter.Ip
                    , Parameter.Mac
                    , userkey));

        return MySign;
    }
    /// <summary>
    /// 执行
    /// </summary>
    /// <returns></returns>
    public override ResponseMessageModel Execute(P model)
    {
        var timeSpan = new TimeSpan(0, 5, 0);

        _mutex.Wait(timeSpan);

        try
        {
            //接收参数
            Parameter = model;

            //执行验证
            if (!Validate())
            {
                return Result;
            }

            //执行业务方法
            ExecuteMethod();
        }
        catch (Exception ex)
        {
            #region 异常处理
            Result.Rows = null;
            Result.Data = null;
            Result.Code = "500";
            Result.Msg = ex.Message;
            Result.IsSuccess = false;

            //StringBuilder DebugeInfo = new StringBuilder();
            //DebugeInfo.Append("Parameter:" + JsonConvert.SerializeObject(this.Parameter) + "\r\n");
            //DebugeInfo.Append("Exception:" + ex.Message + "|" + ex.StackTrace + "\r\n");
            // LoggerFactory.Instance.Logger_Debug(DebugeInfo.ToString(), "ExecuteMethodError");
            #endregion
        }

        // 异步锁释放
        _mutex.Release();

        return Result;
    }
}

